package com.zucc.eye.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zucc.eye.dto.IssueDto;
import com.zucc.eye.dto.RepoDto;
import com.zucc.eye.entity.History;
import com.zucc.eye.entity.Issue;
import com.zucc.eye.entity.Repo;
import com.zucc.eye.repository.HistoryRepository;
import com.zucc.eye.repository.IssueRepository;
import com.zucc.eye.repository.RepoRepository;
import com.zucc.eye.util.HttpUtil;
import com.zucc.eye.util.JsonUtil;
import com.zucc.eye.util.OkHttpUtil;
import com.zucc.eye.util.ReturnT;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhengkai.blog.csdn.net
 * @description issue
 * @date 2022-02-09
 */

@Slf4j
@Api(tags = "issue")
@CrossOrigin
@RestController
@RequestMapping("/issue")
public class IssueController {

    @Autowired
    private IssueRepository issueRepository;

    @Autowired
    private HistoryRepository historyRepository;

    //    @Resource
//    HttpUtil httpUtil;
    @PostMapping("/reqIssNum")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object reqIssNum(@RequestBody Issue issue) {

        //https://api.github.com/repos/moshowgame/SpringBootCodeGenerator
        try{
            String url = issue.getUrl();
//        HttpUtil.
//                httpUtil.get
//        okhttp3 异步 怎么在springboot里面返回

            String string = OkHttpUtil.get(url, null);
            JSONObject jsonObject = JsonUtil.stringToJson(string);
            //这是所有的 info
            //是所有的列表吗
            log.info("jsonObject {}", jsonObject);
            //Repo
            RepoDto repoDto =
                    JSONObject.parseObject(String.valueOf(jsonObject), RepoDto.class);
            Repo repo = repoDto.toEntity();
            //repo
            Integer open_issues = jsonObject.getInteger("open_issues");
            log.info(" open_issues {} ", open_issues);
            return ReturnT.success(open_issues);
        }catch (Exception e){
            e.printStackTrace();
            return  ReturnT.error(e.getMessage());
        }



        //okhttp3.Request request = new okhttp3.Request.Builder().
        //        url(url).get().build();
        //OkHttpClient okHttpClient = new OkHttpClient();
        //final Call call = okHttpClient.newCall(request);
        //call.enqueue(new Callback() {
        //    @Override
        //    public void onFailure(Call call, IOException e) {
        //        log.info("getMessage {}", e.getMessage());
        //    }
        //
        //    @Override
        //    public void onResponse(Call call, okhttp3.Response response) throws IOException {
        //        String string = response.body().string();
        //        //string不能调用两次 被调用一次就关闭了，这里调用两次会报异常
        //        //JSONObject.toString
        //        //JsonUtil.
        //        //str转化 json alibaba
        //        //total_issues = repoInfo.open_issues;
        //        JSONObject jsonObject = JsonUtil.stringToJson(string);
        //        //这是所有的 info
        //        //是所有的列表吗
        //        log.info("jsonObject {}", jsonObject);
        //        Integer open_issues = jsonObject.getInteger("open_issues");
        //        log.info(" open_issues {} ", open_issues);
        //
        //    }
        //});

//————————————————
//        版权声明：本文为CSDN博主「_无问西东」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
//        原文链接：https://blog.csdn.net/weixin_36709064/article/details/81637693
    }

    public Object getIssueByApi( String url){
        //issueForm.
        String s = OkHttpUtil.get(url, null);
        log.info("s {}", s);
        //List<Issue> issues = JSONObject.parseArray(s, Issue.class);
        //List<IssueDto> issueDtos = JSONObject.parseArray(s, IssueDto.class);
        IssueDto issueDto = JSONObject.parseObject(s, IssueDto.class);
        //new Issue()
        log.info("issueDto {}", issueDto);
        Issue issue = issueDto.toEntity();
        log.info("issue {}", issue);
        Issue save = issueRepository.save(issue);
        log.info("save {} ",save);
        //IssueDto issueDto1 = new IssueDto(save);
        //return ReturnT.success(issue);
        return ReturnT.success(issueDto);

    }
    @PostMapping("/getIssue")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object getIssue(@RequestBody Issue issue) {
        //issue.
        String url = issue.getUrl();
        Issue firstByUrl = issueRepository.findFirstByUrl(issue.getUrl());
        //这个应该只有一个的吧
        log.info("firstByUrl {} ",firstByUrl);
        if(firstByUrl==null){

            return  getIssueByApi(url);
        }
        //firstByUrl.to
        //IssueDto issueDto = new IssueDto(issue);
        IssueDto issueDto = new IssueDto(firstByUrl);
        log.info("issueDto {} ",issueDto);
        return ReturnT.success(issueDto);
        //return ReturnT.success(firstByUrl);
    }

    //获取的是 github首页信息
    @PostMapping("/issues")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object issues(@RequestBody Issue issue) {
        String url = issue.getUrl();
        //这是一个的issue
        //那么一个repo的 issues 怎么说
        //获取他的所有issues  是比较赚的 因为一个请求获得 一个列表 所以也没必要查看cache
        //主要是不知道怎么查看列表 全部查看 也不好弄 要是有多了一个 也不能说就用cache了
        //issueRepository.findFirstByUrl()
        //History.builder().
        //Hi
        History byUrl = historyRepository.findByUrl(url);
        if (byUrl==null) {
            //新的
            Date date = new Date();
            History build = History.builder().createTime(date).
                    updateTime(date).url(url).build();
            historyRepository.save(build);
            //return ReturnT.success("")
        }else {
            byUrl.setCreateTime(new Date());
            historyRepository.save(byUrl);
        }
        //historyRepository.save()
        String s = OkHttpUtil.get(url, null);
        log.info("s {}", s);
        //List<Issue> issues = JSONObject.parseArray(s, Issue.class);
        List<IssueDto> issueDtos = JSONObject.parseArray(s, IssueDto.class);
        List<Issue> collect = issueDtos.stream().map(o -> {
            Issue issue1 = o.toEntity();
            return issue1;
        }).collect(Collectors.toList());
        log.info("collect {}",collect);
        List<Issue> issues = issueRepository.saveAll(collect);
        log.info("issues {}",issues);


        JSONArray objects = JSONObject.parseArray(s);
        log.info("objects {}", objects);
        //https://api.github.com/repos/moshowgame/SpringBootCodeGenerator/issues
        //JSONObject json = OkHttpUtil.getJson(url, null);
        //log.info("json {}", json);
        return ReturnT.success(objects);
    }

    /**
     * 新增或编辑
     */
    @PostMapping("/save")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object save(@RequestBody Issue issue) {
        try {
            return ReturnT.success(issueRepository.save(issue));
        } catch (Exception e) {
            e.printStackTrace();
            return ReturnT.error("保存失败");
        }

    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "delete Issue", notes = "delete Issue")
    public Object delete(int id) {
        Optional<Issue> issue = issueRepository.findById(id);
        if (issue.isPresent()) {
            issueRepository.deleteById(id);
            return ReturnT.success("删除成功");
        } else {
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
     * 查询
     */
    @PostMapping("/find")
    @ApiOperation(value = "find Issue by id", notes = "find Issue by id")
    public Object find(int id) {
        Optional<Issue> issue = issueRepository.findById(id);
        if (issue.isPresent()) {
            return ReturnT.success(issue.get());
        } else {
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
     * 分页查询
     */
    @PostMapping("/list")
    @ApiOperation(value = "list Issue", notes = "list Issue")
    public Object list(@RequestBody Issue issue,
                       @RequestParam(required = false, defaultValue = "0") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10") int pageSize) {

        try {
            //创建匹配器，需要查询条件请修改此处代码
            ExampleMatcher matcher = ExampleMatcher.matchingAll();

            //创建实例
            Example<Issue> example = Example.of(issue, matcher);
            //分页构造
            Pageable pageable = PageRequest.of(pageNumber, pageSize);

            return ReturnT.success(issueRepository.findAll(example, pageable));

        } catch (Exception e) {
            e.printStackTrace();
            return ReturnT.error(e.getMessage());
        }

    }

}